import { defineStore } from 'pinia';
import axios from '../utils/axios';

// API基础URL - 已经在axios配置中设置了baseURL，这里保持定义以便于理解

export const useUserStore = defineStore('user', {
  state: () => ({
    userInfo: null,
    loading: false,
    error: null
  }),

  getters: {
    userAvatar: (state) => state.userInfo?.avatar || '',
    isLoggedIn: () => !!localStorage.getItem('token'),
    userName: (state) => state.userInfo?.name || '未登录'
  },

  actions: {
    // 设置用户信息
    setUserInfo(userInfo) {
      this.userInfo = userInfo;
    },

    // 获取用户信息
    async fetchUserInfo() {
      try {
        if (!localStorage.getItem('token')) return;

        const response = await axios.get('/users/current');
        this.setUserInfo(response);

        return response;
      } catch (error) {
        console.error('获取用户信息失败:', error);
        // 处理token过期或无效的情况
        if (error.response?.status === 401) {
          this.logout();
        }
      }
    },

    // 更新用户信息
    async updateUserInfo(userData) {
      try {
        this.loading = true;
        this.error = null;

        const response = await axios.put('/users/current', userData);

        this.setUserInfo(response);

        return response;
      } catch (error) {
        this.error = error.response?.message || '更新失败';
        throw error;
      } finally {
        this.loading = false;
      }
    },

    // 登出
    logout() {
      this.setUserInfo(null);
      // 清除其他相关数据
      localStorage.removeItem('token');
    },

    // 清除错误信息
    clearError() {
      this.error = null;
    }
  }
});